<?php
// 本方法依赖于wordpress 和 simple_html_dom.php
require_once dirname(__FILE__) . '/wp-load.php';
require_once dirname(__FILE__) . '/simplehtmldom/simple_html_dom.php';

//有道翻译需要毫秒级时间搓来作为salt
function get_total_millisecond()
{
    $time = explode(" ", microtime());
    $time = $time[1] . (number_format($time[0], 4, '.', '') * 1000);
    $time2 = explode(".", $time);
    $time = $time2[0];
    return $time;
}

/*
 * $url = "http://demo50.huaqiutong.com/contact/";
 * $form = "en";
 * $to = "zh-CHS";
 * */
function request_youdao_web_fanyi($goalUrl, $formLanguage, $toLanguage)
{
    $product = "mdictweb";
    $salt = get_total_millisecond();
    $sign = md5($product . $salt . 'ydsecret://mdictweb.si/sign/-eV=8}L$s4$nPL00op3p]' . urldecode($goalUrl));
    $urlencode = urlencode($goalUrl);
    $Referer = "http://webtrans.yodao.com/webTransPc/index.html?from={$formLanguage}&to={$toLanguage}&type=1&url={$urlencode}";
    $youdao_web_fanyi_url = "http://webtrans.yodao.com/server/webtrans/tranUrl?url={$urlencode}&from={$formLanguage}&to={$toLanguage}&type=1&product={$product}&salt={$salt}&sign={$sign}";
    $args = array(
        'headers' => array(
            'Referer' => $Referer,
            'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
            'Upgrade-Insecure-Requests' => 1,
            'Host' => 'webtrans.yodao.com',
            'timeout' => 60,
        ),
    );
    return wp_remote_retrieve_body(wp_remote_get($youdao_web_fanyi_url, $args));
}

//过滤文本获得翻译的内容
function youdaoRemoveRedundantParameters($content, $formLanguage = 'en', $toLanguage = 'zh', $delete_host, $baoliu_host, $part = null)
{
    if ($toLanguage == 'zh-CHS') {
        $toLanguage = 'zh';
    }
    if ($part == null) {
        //a标签url 过滤 百度翻译替换的url 换回自己的url
        $part = '/"http:\/\/webtrans\.yodao\.com\/server\/webtrans\/tranUrl\?url=(.*?)&(amp;)from=(.*?)&(amp;)to=(.*?)&(amp;)type=1&(amp;)product=mdictweb&(amp;)salt=(.*?)&(amp;)sign=(.*?)"/';
    }
    if (is_string($delete_host)) {
        $delete_host = array($delete_host);
    }
    //去掉多余字符串 <script type=text/javascript>document.createElement('trans'); </script>
    $content = str_replace("document.createElement('trans');", "", $content);
    $content = preg_replace('/<base.*?>/is', '', $content);
    preg_match_all($part, $content, $matches);
    foreach ($matches[0] as $key => $value) {
        $get_url = urldecode($matches[1][$key]);
        $needurl = "/" . $toLanguage . "/" . rtrim(str_replace($delete_host, '', $get_url), '/') . ".html";
        if (in_array($get_url, $delete_host)) {
            $needurl = "/" . $toLanguage . "/" . "index.html";
        }
        if (substr($get_url, 0, 4) == 'tel:' || substr($get_url, 0, 7) == "mailto:" || substr($get_url, 0, 1) == '#' || in_array($get_url, $baoliu_host)) {
            $needurl = $get_url;
        }
        $content = str_replace($value, '"' . $needurl . '"', $content);
    }
    return $content;
}

//创建百度翻译并返回内容
function request_baidu_fanyi($goalUrl, $formLanguage, $toLanguage)
{
    $goalUrl = urlencode($goalUrl);
    $url = "http://translate.baiducontent.com/transpage?query={$goalUrl}&from={$formLanguage}&to={$toLanguage}&source=url&frzj=cfy";
    $Referer = "http://fanyi.baidu.com/transpage?query={$goalUrl}&source=url&ie=utf8&from={$formLanguage}&to={$toLanguage}&render=1";
    $args = array(
        'headers' => array(
            'Referer' => $Referer,
            'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
            'Upgrade-Insecure-Requests' => 1,
            'Host' => 'translate.baiducontent.com',
            'timeout' => 60,
        ),
    );
    return wp_remote_retrieve_body(wp_remote_get($url, $args));
}

//去掉翻译多余的a标签的参数, urlOrContent ture 代表返回url,false代表返回内容 假冒的函数 还不知道谷歌的 先这样
function baiduRemoveRedundantParameters($content, $formLanguage = 'en', $toLanguage = 'zh', $delete_host, $baoliu_host, $part = null)
{
    if (!$part) {
        //a标签url 过滤 百度翻译替换的url 换回自己的url
        $part = "/https:\/\/translate\.baiducontent\.com\/transpage\?cb=translateCallback&(amp;)?ie=utf8&(amp;)?source=url&(amp;)?query=(.*?)&(amp;)?from={$formLanguage}&(amp;)?to={$toLanguage}&(amp;)?token=(.*?)&(amp;)?monLang=zh/";
    }
    if(is_string($delete_host)){
 	$delete_host = array($delete_host);
    }
    //去掉多余字符串 <script type=text/javascript>document.createElement('trans'); </script>
    $content = str_replace("document.createElement('trans');", "", $content);
    preg_match_all($part, $content, $matches);
    foreach ($matches[0] as $key => $value) {
        $get_url = urldecode($matches[4][$key]);
	$del_delete_host_after = rtrim(str_replace($delete_host, '', $get_url), '/');
        if($del_delete_host_after){
            $needurl = "/" . $toLanguage . "/" . $del_delete_host_after . ".html";
        }else{
            $needurl = "/" . $toLanguage . "/index.html";
	}
        if (in_array($get_url, $delete_host) || $get_url == '/' || $get_url == "") {
            $needurl = "/" . $toLanguage . "/" . "index.html";
        }
        if (substr($get_url, 0, 23) == 'https://www.google.com/' || substr($get_url, 0, 4) == 'tel:' || substr($get_url, 0, 1) == '#' || in_array($get_url, $baoliu_host)) {
            $needurl = $get_url;
        }

        $content = str_replace($value, $needurl, $content);
    }

    $content = preg_replace('/<trans.*?>/is', '', $content);
    $content = preg_replace('/<base.*?>/is', '', $content);
    $content = preg_replace('/<\/trans>/is', '', $content);
    return $content;

}

function formPathBasedOnTheURL($url, $dir)
{
    $temp = parse_url($url);
    if ($temp['path'] == "/" || $temp['path'] == "") {
        return $dir . "/index.html";
    }
    return $dir . rtrim($temp['path'], '/') . ".html";
}

//写入内容到指定文件
function writeContentToHtml($filePath, $fileContent)
{
    $fileDir = substr($filePath, 0, strripos($filePath, '/'));
    if (!is_dir($fileDir)) {
        if (!wp_mkdir_p($fileDir)) {
            return false;
        }
    }
    @$handle = fopen($filePath, "a");
    if (!$handle) {
        return false;
    }
    fwrite($handle, $fileContent);
    fclose($handle);
    return true;
}
//获得网址的域名和协议组成的参数
function get_url_domain_protocol_path($url)
{
    $temp = parse_url($url);
    return $temp['scheme'] . "://" . $temp['host'];
}

if (class_exists('Redis')) {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    $task = $redis->rpop("translate_task_list");
    $taskdata = json_decode($task, 1);

    if (!$taskdata) {
        die('no task stop');
    }

    $goalurl = $taskdata['goalurl'];
    $source_lang = $taskdata['source_lang'];
    $goal_lang = $taskdata['goal_lang'];
    //感觉有到的还可以 评论和 ip 撒的需要注意 可能 那个user-agent也需要注意 不然就白嫖不成功了
    // $getHtmlContent = str_get_html(request_youdao_web_fanyi($goalurl, $source_lang, $goal_lang));
    //百度就是效果差一点
    $body = request_baidu_fanyi($goalurl, $source_lang, $goal_lang);
    $getHtmlContent = str_get_html($body);
    if ($getHtmlContent) {
        $outhtml = $getHtmlContent->find('html', 0);
    } else {
        $redis->rpush("translate_task_list", $task);
        die('白嫖失败');
    }

    if ($outhtml) {
        $outhtml = $outhtml->outertext();
    } else {
        echo "没有请求成功";
        $redis->rpush("translate_task_list", $task);
        die;
    }

    $delete_host = get_url_domain_protocol_path($goalurl);
    //保留地址 让他不变样
    $baoliu_host = array("https://www.huaqiutong.com", "https://www.huaqiutong.com/");

    $content = baiduRemoveRedundantParameters($outhtml, $source_lang, $goal_lang, $delete_host, $baoliu_host); 
    $fileDir = $_SERVER['DOCUMENT_ROOT'];
    //$fileDir = "/home/wwwroot/default";
    $fileDir .= "/" . $goal_lang;
    $filePath = formPathBasedOnTheURL($goalurl, $fileDir);
    if (writeContentToHtml($filePath, $content)) {
        echo "生成文件完成: {$filePath}";
    } else {
        echo "生成文件失败";
        $redis->rpush("translate_task_list", $task);
    }
    echo "\r\n";

} else {
    echo "网站不支持Redis模块\r\n";
}

